package controller

import (
	"fmt"
	"math"
	"parking-lot-go-dingding/model/cars"

	"github.com/gin-gonic/gin"
)

func Consumption(c *gin.Context) {
	requestStruct := struct {
		Keyword string `json:"keyword"`
		Page    int    `json:"page"`
		Limit   int    `json:"limit"`
	}{}

	start := (requestStruct.Page - 1) * requestStruct.Limit

	//接收加密串
	if err := c.ShouldBindJSON(&requestStruct); err != nil {
		Fail(c, "json接收失败")
		return
	}

	var err error

	var carsOutStruct cars.CarsOutStruct
	where := map[string]interface{}{
		"order_type": 3,
	}
	if requestStruct.Keyword != "" {
		where["car_number like ?"] = "%%" + requestStruct.Keyword + "%%"
	}

	list, err := carsOutStruct.List(where)
	if err != nil {
		Fail(c, "记录查询失败")
	}
	count, err := carsOutStruct.Count(where)
	if err != nil {
		Fail(c, "总数查询失败")
	}

	newsReturn := make([]map[string]interface{}, 0)

	for _, v := range list {
		newsReturn = append(newsReturn, map[string]interface{}{
			"car_number": v.CarNumber,
			"park_time":  convertMinutesToDaysHoursMinutes(v.ParkTime),
			"park_name":  v.ParkName,
			"in_time":    v.InTime.Format("2006-01-02 15:04"),
			"out_time":   v.OutTime.Format("2006-01-02 15:04"),
			"charge_amt": v.ChargeAmt,
		})
	}

	Success(c,
		map[string]interface{}{
			"list":         newsReturn,
			"current_page": start,
			"last_page":    math.Ceil(float64(count) / float64(requestStruct.Limit)),
		})
}

func convertMinutesToDaysHoursMinutes(minutes int) string {
	days := minutes / (24 * 60)
	hours := (minutes % (24 * 60)) / 60
	remainingMinutes := minutes % 60
	return fmt.Sprintf("%d天%d小时%d分钟", days, hours, remainingMinutes)
}
